using OpenBlock.Terrain;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;

namespace OpenBlock.IO
{
    public class LevelManager
    {
        public string savePath;
        public static string LevelDirectoryPath => Path.Combine(Application.persistentDataPath, "levels");

        public Queue<(Task<Chunk>, System.Action<Chunk>)> loadTaskQueue = new Queue<(Task<Chunk>, System.Action<Chunk>)>();
        public LevelManager()
        {
            savePath = Application.persistentDataPath;
        }

        public static void CreateLevel(LevelInfo info)
        {
            var levelInfoFile = JsonUtility.ToJson(info);
            var curLevelDir = Directory.CreateDirectory(Path.Combine(LevelDirectoryPath, info.levelName));
            var chunksDir = Directory.CreateDirectory(Path.Combine(curLevelDir.FullName, "chunks"));
            File.WriteAllText(Path.Combine(curLevelDir.FullName, "level_info.json"), levelInfoFile);
        }

        public static LevelInfo[] GetLevels()
        {
            var levels = new List<LevelInfo>();
            foreach (var levelDir in Directory.GetDirectories(LevelDirectoryPath))
            {
                var infoPath = Path.Combine(levelDir, "level_info.json");
                if (!File.Exists(infoPath)) continue;

                var levelInfo = JsonUtility.FromJson<LevelInfo>(File.ReadAllText(infoPath));
                levels.Add(levelInfo);
            }

            return levels.ToArray();
        }

        public void HandleTasks()
        {
            if (loadTaskQueue.Count != 0)
            {
                for (int i = 0; i < loadTaskQueue.Count; i++)
                {
                    var (task, action) = loadTaskQueue.Dequeue();
                    if (task.IsCompleted)
                    {
                        action(task.Result);
                    }
                    else
                    {

                    }
                }
            }
        }

        public void SaveChunkRequest(string levelName, Chunk chunk)
        {
            
        }

        public void LoadChunkRequest(string levelName, Vector3Int position, System.Action<Chunk> onFinishLoad)
        {
            
        }
    }
}